﻿using System;
using System.Linq;
using PostSharp.Aspects;

namespace YuYuKiCms.Framework.Aspect
{
    /// <summary>
    ///     Cette class va controller si un des arguments passé en paramètre est null
    /// </summary>
    [Serializable]
    public class ThrowArgumentNullExceptionAspectAttribute : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            // Get index of null value
            var indexOfNullParameters = args.Arguments
                .Select((valeur, index) => new {index, valeur})
                .Where(arg => arg.valeur == null)
                .Select(x => x.index)
                .ToArray();

            if (!indexOfNullParameters.Any())
                return;

            // Get null parameters
            var nullParameters = args.Method.GetParameters()
                .Where(f => indexOfNullParameters
                    .Any(o => o.Equals(f.Position))
                )
                .Select(f => f.Name)
                .Aggregate((m, n) => m + ", " + n);

            // Get methode name
            var methodeName = args.Method.Name;
            throw new ArgumentNullException(nullParameters,
                string.Format("The method {0} has taken some null parameters.", methodeName));
        }
    }
}